package com.dhcc.logs.aspect;
 
 
import java.lang.reflect.Method;
import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.dhcc.logs.common.annotation.Log;
import com.dhcc.logs.common.enums.BusinessStatus;
import com.dhcc.logs.common.queue.blockingqueue.LogSaveQueue;
import com.dhcc.logs.common.utils.IPUtils;
import com.dhcc.logs.entity.SysOperLog;
import com.dhcc.logs.service.LogService;
 
/**
 * 操作日志记录处理
 * 
 * @author hk
 */
@Aspect
@Component
public class LogAspect{
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
 
    @Autowired
    private LogService logService;
 
 
    // 配置织入点
    @Pointcut("@annotation(com.dhcc.logs.common.annotation.Log)")
    public void logPointCut(){
    	
    }
    
    @Before("logPointCut()")
    public  void dobefore(){
        log.info("====>切面之前会执行");
    }
 
    /**
           * 在代码执行之后，不论代码成功执行还是抛出异常都会执行到这里
     */
    @After("logPointCut()")
    public  void doAfter(){
        log.info("====>切面执行之后");
    }
 
    @AfterReturning(value = "logPointCut()",returning = "result")
    public  void AfterReturning(Object result){
        log.info("====>执行结果返回值："+result.toString() );
    }
 
 
    /**
           * 前置通知 用于拦截操作
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint){
        handleLog(joinPoint, null);
    }
 
    /**
           * 拦截异常操作
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e){
        handleLog(joinPoint, e);
    }
	protected void handleLog(final JoinPoint joinPoint, final Exception e) {
		try {
			// 获得注解
			Log controllerLog = getAnnotationLog(joinPoint);
			if (controllerLog == null) {
				return;
			}
			// *========数据库日志=========*//
			SysOperLog operLog = new SysOperLog();
			operLog.setLogDate(new Date());//日志日期
			operLog.setStatus(BusinessStatus.SUCCESS.getCode());
			operLog.setOperIp(IPUtils.getIpAddr());// 请求ip
			operLog.setOperUrl(IPUtils.getReqUrl());//请求URL
			operLog.setOperName("system");//实际场景从shiro或者其他里面取用户信息（用户名，部门名）
			if (e != null) {
				operLog.setStatus(BusinessStatus.SERVER_ERROR.getCode());
				operLog.setErrorMsg(e.getMessage().toString());
			}
			// 设置方法名称
			String className = joinPoint.getTarget().getClass().getName();
			String methodName = joinPoint.getSignature().getName();
			operLog.setMethod(className + "." + methodName + "()");
			getControllerMethodDescription(controllerLog, operLog,joinPoint);// 处理设置注解上的参数
			log.info(operLog.toString());
			// 保存数据库，采用消息队列进行保存[blockingqueue,activeMq,rabbitMq,kafka]
//            logService.save(operLog);
            LogSaveQueue.getQueue().produce(operLog);
		} catch (Exception exp) {
			// 记录本地异常日志
			log.error("==LogAspect异常==");
			log.error("异常信息:{}", exp.getMessage());
			exp.printStackTrace();
		}
	}
 
    /**
           * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log 切点
     * @param joinPoint 
     * @return 方法描述
     * @throws Exception
     */
	public void getControllerMethodDescription(Log log, SysOperLog operLog, JoinPoint joinPoint) throws Exception {
		operLog.setBusinessType(log.businessType().ordinal());// 设置action动作
		operLog.setTitle(log.title());// 设置标题
		operLog.setOperatorType(log.operatorType().ordinal());// 设置操作人类别
		// 是否需要保存request，参数和值
		if (log.isSaveRequestData()) {
			//请求参数
			Object[] args = joinPoint.getArgs();
			String params = JSON.toJSONString(args);
			operLog.setOperParam(params);// 获取参数的信息，传入到数据库中。
		}
	}
    /**
           * 是否存在注解，如果存在就获取
     */
	private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();
		if (method != null) {
			return method.getAnnotation(Log.class);
		}
		return null;
	}
 
 
}